// pages/order/orderSubmit/orderSubmit.js
const app = getApp()
import config from '../../../utils/config.js';
import util from '../../../utils/util.js';
import Toast from '../../../vant/toast/toast';
import Dialog from '../../../vant/dialog/dialog';
import {
  orderModel
} from '../../../models/order';
const order = new orderModel();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    config:config,
    nvabarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '提交订单',
      //  导航栏 中间的标题
    },
    height: app.globalData.height,
    navHeight: app.globalData.barheight,

    groupNo:'',
    type:'',    // 1 组订单 2 订单
    detail:{},
    stallName:'',    // 档口名称

    // date: '', //默认起始时间  
    // date2: '',//限制开始时间 
    // maxDate:'',

    date: '',//默认起始时间  
    date1: '',//默认结束时间 
    minDate: new Date().getTime()+60*60*1000,
    // maxDate: 0,
    currentDate: new Date().getTime()+24*60*60*1000, 
    formatter(type, value) {
      if (type === 'seconds') {
        return '';
      }
      return value;
    },
    show: false,

    remarks:'', // 备注
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      groupNo:options.id,
      type:options.type
    })
    // console.log(this.data.type);
    this.selectDetail()

    this.data.fLoad = true

    // var day3 = new Date();
    // day3.setTime(day3.getTime()+24*60*60*1000);
    // var s3 = day3.getFullYear()+"/" + (day3.getMonth()+1) + "/" + day3.getDate() + " 00:00:00";
    // // console.log(s3)
    // this.setData({ 
    //   currentDate: new Date(s3).getTime(),
    // })
    // var nowDate = new Date()
    // var year = nowDate.getFullYear()
    // var mouth = nowDate.getMonth()+1
    // var day = nowDate.getDate()
    // var maxDate = year+'-'+mouth+'-'+day
    // this.setData({
    //   date2: maxDate,
    //   maxDate: maxDate
    // })
  },
  // 日期选择  
  // bindDateChange(e) {
  //   let that = this;
  //   console.log(e.detail.value)
  //   that.setData({
  //     date: e.detail.value,
  //   })
  // },
  // 日期选择  
  onDeliveryTime(e) {
    this.setData({
      show: true
    })
  },
  onConfirm(event) {
    var date = util.formatTimeTwo(event.detail,'Y-M-D h:m')
    var minDate1 = event.detail

    this.setData({
      currentDate: event.detail,
      date: date,
      show: false,
      // minDate1: minDate1
    });
  },
  onCancel0(){
    this.setData({
      show: false
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  selectDetail(){
    if(this.data.type==2){
      order.apiOrderDetail({shopOrderNo:this.data.groupNo}, res => {
        if(res.deliveryTime){
          var currentDate = new Date(res.deliveryTime.replace(/-/g,'/')).getTime();
          var date = util.formatTimeTwo(currentDate,'Y-M-D h:m')
          this.setData({
            date: date,
            currentDate: currentDate
          })
        }
        this.setData({
          remarks: res.remarks?res.remarks:'',
          detail:res
        })
        this.getStallName(res.singleOrderInfoVoList);
      })
    }else{
      order.apiOrderDetailMs({groupNo:this.data.groupNo}, res => {
        if(res.deliveryTime){
          var currentDate = new Date(res.deliveryTime.replace(/-/g,'/')).getTime();
          var date = util.formatTimeTwo(currentDate,'Y-M-D h:m')
          this.setData({
            date: date,
            currentDate: currentDate
          })
        }
        this.setData({
          remarks: res.remarks?res.remarks:'',
          detail:res
        })
        this.getStallName(res.singleOrderInfoVoList);
      })
    }
  },

  getStallName(list){
    var nameSrr = [];
    if(list && list.length>0){
        for(var i=0;i<list.length;i++){
          nameSrr.push(list[i].stallName);
        }
    }
    var newName = Array.from(new Set(nameSrr))
    var stallName = '';
    for(var i=0;i<newName.length;i++){
      stallName += newName[i]
    }
    this.setData({
      stallName:stallName
    })
  },

  onInput(event) {
    this.setData({
      currentDate: event.detail,
    });
  },

  // 备注
  onRemarks(event){
    this.setData({
      remarks: event.detail
    })
  },

  // 查看更多商品列表
  orderImg(){
    wx.navigateTo({
      url: '/pages/order/orderSubmit/orderCList/orderCList?id='+this.data.groupNo+'&type='+this.data.type,
    })
  },

  // 提交订单
  submintOrder: util.throttle(function (e) {
    if(!this.data.date){
      util.msg('请选择交货日期');
      return;
    }
    console.log(this.data.detail);
    if(!this.data.groupNo){
      util.msg('加载异常');
      return;
    }
    // const params = {
    //   deliveryTime: this.data.date,
    //   goodList: [
    //     {
    //       goodCount: 0,
    //       goodId: "",
    //       stallId: 0
    //     }
    //   ],
    //   remarks: this.data.remarks,
    //   shopOrderNo: this.data.groupNo
    // }
    // for(const i of this.data.detail.singleOrderInfoVoList){
    //   params.goodList.push({
    //     goodCount: i.goodCount,
    //     goodId: i.goodId,
    //     stallId: i.stallId
    //   })
    // }
    if(this.data.type==2){
      // 订单提交
      order.apiSubmitOrder({
        shopOrderNo:this.data.groupNo,
        deliveryTime:this.data.date,
        remarks:this.data.remarks
      }, res => {
        // 结账类型 1 立结 2 记账
        var billType = this.data.detail.billType;
        if(billType==1){
          this.onWeixin();
        }else{
          Toast.success('操作成功');
          this.onBook();
        }
      })  
      
      // order.apiSubmitOrderV2(JSON.stringify(params), res => {
      //   // 结账类型 1 立结 2 记账
      //   var billType = this.data.detail.billType;
      //   if(billType==1){
      //     this.onWeixin();
      //   }else{
      //     Toast.success('操作成功');
      //     this.onBook();
      //   }
      // }) 
    }else{
      // 组订单提交
      order.apiSubmitOrderMs({
        shopOrderNo:this.data.groupNo,
        deliveryTime:this.data.date,
        remarks:this.data.remarks
      }, res => {
        // 结账类型 1 立结 2 记账
        var billType = this.data.detail.billType;
        if(billType==1){
          this.onWeixin();
        }else{
          Toast.success('操作成功');
          this.onBook();
        }
      }) 
      // order.apiSubmitOrderMsV2(JSON.stringify(params), res => {
      //   // 结账类型 1 立结 2 记账
      //   var billType = this.data.detail.billType;
      //   if(billType==1){
      //     this.onWeixin();
      //   }else{
      //     Toast.success('操作成功');
      //     this.onBook();
      //   }
      // }) 
    }
    
  }),

  // 记账直接跳转至订单卡片
  onBook(){
    var that = this;
    setTimeout(function () {
      if(that.data.type==2){
        wx.navigateBack({
          delta: 1,
        })
      }else{
        wx.switchTab({
          url: '/pages/order/order',
        })
      }
      
    }, 1000);
  },

  // 假的微信支付
  // onWeixin(){
  //   var that = this
  //   if(this.data.type==2){
  //     order.payNotifytest({
  //       shopOrderNo: this.data.groupNo
  //     }, res => {
  //       if (res.code == 200) {
  //         Toast.success('支付成功');
  //         this.onBook();
  //       } else {
  //         util.msg(res.msg)
  //       }
  //     })
  //   }else{
  //     order.payNotifytestMs({
  //       groupNo: this.data.groupNo
  //     }, res => {
  //       if (res.code == 200) {
  //         Toast.success('支付成功');
  //         this.onBook();
  //       } else {
  //         util.msg(res.msg)
  //       }
  //     })
  //   }
    
  // },

  // 微信支付
  onWeixin(){ 
    var openId = wx.getStorageSync('openid')
    order.releaseWXPay({
      groupNo: this.data.groupNo,
      openId:openId
    }, res => {
      if (res.code == 200) {
        this.processPay(res.data)
      } else {
        util.msg(res.msg)
      }
    })
  },
  /* 小程序支付 */
  processPay: function (param) { // 调起支付
    var that = this
    wx.requestPayment({
      timeStamp: param.timeStamp,
      nonceStr: param.nonceStr,
      package: param.package,
      signType: param.signType,
      paySign: param.paySign,
      success: function (res) {
        console.log("wx.requestPayment返回信息", res);
        that.onBook()
      },
      fail: function () {
        console.log("支付失败");
        Dialog.confirm({
          title: '支付失败',
          message: '支付遇到问题，请尝试重新支付',
          confirmButtonText: '重新支付',
          cancelButtonText: '取消'
        }).then(() => {
          that.onWeixin()
        }).catch(() => {
          // on cancel
          wx.navigateBack()
        });
      },
      complete: function () {
        console.log("支付完成(成功或失败都为完成)");
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})